package classes
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	
	import mx.collections.ArrayCollection;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.mxml.HTTPService;

	public class QbnHandler extends EventDispatcher
	{
		private static var instance:QbnHandler;
		private var _tagList:ArrayCollection;
		private var _lastResult:ArrayCollection;
		
		[Bindable ("qbnResult")]
		public function get lastResult():ArrayCollection{
			return _lastResult;
		}
		[Bindable ("qbnResult")]
		public function get tagList():ArrayCollection{
			return _tagList;
		}		
		public function QbnHandler(target:IEventDispatcher=null){
			super(target);
		}
		
		public function performQbn(theImageURI:String):void{
			dispatchEvent(new Event("performingQbn"));
			var servletReq:HTTPService = new HTTPService();
			servletReq.method = "POST";
			servletReq.url = Settings.getInstance().qbnServletURL;
			servletReq.addEventListener(ResultEvent.RESULT, qbnResultHandler);
			servletReq.send({"imageURI": theImageURI});
		}
		
		private function qbnResultHandler(event:ResultEvent):void{
		//	trace(event.result);
			_lastResult = Parser.parseServletResult(event);
			if(_lastResult == null){
				dispatchEvent(new Event("qbnError"));
			}else{
				_tagList = getUniqueTagList(_lastResult);
				dispatchEvent(new ResultEvent("qbnResult",false,true,_lastResult));
			}
		}
		
		private function getUniqueTagList(imgs:ArrayCollection):ArrayCollection{
			var tags:ArrayCollection = new ArrayCollection;
			for each(var img:ReturnedImage in imgs){
				for each(var tag:String in img.tags){
					if(!tags.contains(tag))
						tags.addItem(tag);
				}
			}
			return tags;
		}

		public static function getInstance():QbnHandler{
			if(instance == null)
				instance = new QbnHandler();
			return instance;
		}
	}
}